<?php
// +----------------------------------------------------------------------
// | INPHP
// | Copyright (c) 2023 https://inphp.cc All rights reserved.
// | Licensed ( https://opensource.org/licenses/MIT )
// | Author: 幺月儿(https://gitee.com/lulanyin) Email: inphp@qq.com
// +----------------------------------------------------------------------
// | 图形验证码
// | 默认使用SessionID作为保存临时二维码的缓存键名
// | 但是，若是客户端非浏览器，无cookie的情况，需要由客户端指定验证码ID，服务端将使用ID+IP混合MD5后作为缓存键名
// +----------------------------------------------------------------------
namespace app\sso\http\api;

use Inphp\Core\Services\Http\Response;
use Inphp\Core\Util\Str;
use Intervention\Image\ImageManagerStatic as Image;

class vCode
{
    public function index(): Response
    {
        //是否需要指定ID
        $id = GET("id");
        $id = !empty($id) ? Str::trim($id) : 0;
        //生成临时验证码
        $value = setVCode(4, $id);
        //在中间插入空隔
        $string = str_split($value);
        $vCode = $string[0];
        for ($i=1; $i<4; $i++) {
            $vCode .= " ".$string[$i];
        }
        $img = Image::canvas(240, 96, "#ffffff");
        for($i=0; $i<30; $i++) {
            @$img->line(mt_rand(0, 240), mt_rand(0, 120), mt_rand(0, 240), mt_rand(0, 120), function ($draw) {
                $draw->color("#333333");
            });
        }
        $img->text(strtoupper($vCode), 20, 20, function ($font) {
            $font->file(__DIR__."/../../font/vcode.ttf");
            $font->size(80);
            $font->color("#000000");
            $font->valign("top");
        });
        $stream = $img->stream("jpeg", 100);
        return httpResponse($stream, Response::CONTENT_TYPE_IMAGE_JPEG);
    }
}